﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace System.Net.Http
{
    /// <summary>
    /// HttpClient 扩展
    /// </summary>
    public static class HttpClientExtensions
    {
        /// <summary>
        /// 读取接口返回的json格式数据转换为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="httpContent"></param>
        /// <returns></returns>
        public static async Task<T> ReadAsync<T>(this HttpContent httpContent)
        {
            var media = httpContent.Headers.ContentType.MediaType;

            if (!media.Equals("application/json", StringComparison.InvariantCultureIgnoreCase))
                throw new FormatException("接口返回值非application/json");

            using (var stream = await httpContent.ReadAsStreamAsync())
            using (StreamReader sr = new StreamReader(stream))
            using (JsonTextReader jsonReader = new JsonTextReader(sr))
            {
                return new JsonSerializer().Deserialize<T>(jsonReader);
            }
        }


        /// <summary>
        /// post提交数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="client"></param>
        /// <param name="requestUri"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, string requestUri, T value)
        {
            string jsonString = JsonConvert.SerializeObject(value);
            StringContent stringContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
            return client.PostAsync(requestUri, stringContent); 
        }


    }
}
